package com.ldxiwxr.framework.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ldxiwxr.framework.constant.SaTokenConstant;
import com.ldxiwxr.system.entity.Role;
import com.ldxiwxr.system.entity.User;
import com.ldxiwxr.system.entity.UserRole;
import com.ldxiwxr.system.mapper.RoleMapper;
import com.ldxiwxr.system.mapper.UserMapper;
import com.ldxiwxr.system.mapper.UserRoleMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


/**
 * Sa-Token 配置类
 * @author SuBanxia
 */
@RequiredArgsConstructor
@Configuration
public class SaTokenConfig implements WebMvcConfigurer, StpInterface {
    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    private final SaTokenConstant saTokenConstant;

    /**
     * 注册sa-token的拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // 注册 Sa-Token 拦截器，校验规则为 StpUtil.checkLogin() 登录校验。
        registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))
                .addPathPatterns("/**")
                .excludePathPatterns(saTokenConstant.getExclude());
    }

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return null;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 创建list对象
        List<String> list = new ArrayList<String>();
        // 创建wrapper对象，查询一个role对象
        LambdaQueryWrapper<UserRole> wrapper = Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId, loginId);
        UserRole userRole = userRoleMapper.selectOne(wrapper);
        Role role = roleMapper.selectById(userRole.getRoleId());
        //将对应的权限填入list
        list.add(role.getRoleName());
        return list;
    }
}

